package sw6.admin.gui.logic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * This class is used to serialize objects to byte arrays, and de-serialize byte arrays to objects
 * @author sw6b
 *
 */
public class Serializer {
	
	/**
	 * 
	 * @param object
	 * @return A serialized byte array 
	 */
	public static byte[] serializeObject(Object object) {

		ByteArrayOutputStream baos  = new ByteArrayOutputStream();
		ObjectOutputStream oos   = null;
		try {
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return baos.toByteArray();
	}

	public static <T> T deSerializeObject(byte[] bytes, Class<T> someClass ) {

		ByteArrayInputStream bais   = new ByteArrayInputStream(bytes);
		ObjectInputStream ois    = null;

		Object obj = null;
		try {
			ois = new ObjectInputStream(bais);
			obj = ois.readObject();
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return someClass.cast(obj);
	}
}